/**
 * 更新头盔装备base值的脚本
 * 功能：根据头盔数据更新equipment_base表中对应头盔的base值
 */

const mysql = require('mysql2/promise');

// 数据库连接配置
const dbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

// 头盔数据映射 (type=1)
const helmetData = {
    // base=1: 武类头盔
    1: [
        { id: 132, name: "草帽·武", lvl: 1, price: 1500 },
        { id: 133, name: "布帽·武", lvl: 2, price: 3000 },
        { id: 134, name: "皮帽·武", lvl: 3, price: 6000 },
        { id: 135, name: "皮盔·武", lvl: 4, price: 12000 },
        { id: 136, name: "铁盔·武", lvl: 5, price: 24000 },
        { id: 137, name: "钢盔·武", lvl: 6, price: 48000 },
        { id: 138, name: "铜盔·武", lvl: 7, price: 96000 },
        { id: 139, name: "银冠·武", lvl: 8, price: 192000 },
        { id: 140, name: "金冠·武", lvl: 9, price: 384000 },
        { id: 141, name: "龙冠·武", lvl: 10, price: 768000 }
    ],
    // base=2: 文类头盔
    2: [
        { id: 142, name: "草帽·文", lvl: 1, price: 1500 },
        { id: 143, name: "布帽·文", lvl: 2, price: 3000 },
        { id: 144, name: "皮帽·文", lvl: 3, price: 6000 },
        { id: 145, name: "皮盔·文", lvl: 4, price: 12000 },
        { id: 146, name: "铁盔·文", lvl: 5, price: 24000 },
        { id: 147, name: "钢盔·文", lvl: 6, price: 48000 },
        { id: 148, name: "铜盔·文", lvl: 7, price: 96000 },
        { id: 149, name: "银冠·文", lvl: 8, price: 192000 },
        { id: 150, name: "金冠·文", lvl: 9, price: 384000 },
        { id: 151, name: "龙冠·文", lvl: 10, price: 768000 }
    ],
    // base=3: 异类头盔
    3: [
        { id: 152, name: "草帽·异", lvl: 1, price: 1500 },
        { id: 153, name: "布帽·异", lvl: 2, price: 3000 },
        { id: 154, name: "皮帽·异", lvl: 3, price: 6000 },
        { id: 155, name: "皮盔·异", lvl: 4, price: 12000 },
        { id: 156, name: "铁盔·异", lvl: 5, price: 24000 },
        { id: 157, name: "钢盔·异", lvl: 6, price: 48000 },
        { id: 158, name: "铜盔·异", lvl: 7, price: 96000 },
        { id: 159, name: "银冠·异", lvl: 8, price: 192000 },
        { id: 160, name: "金冠·异", lvl: 9, price: 384000 },
        { id: 161, name: "龙冠·异", lvl: 10, price: 768000 }
    ]
};

class HelmetBaseUpdater {
    constructor() {
        this.connection = null;
        this.dbConfig = dbConfig;
    }

    // 建立数据库连接
    async connect() {
        try {
            this.connection = await mysql.createConnection(this.dbConfig);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async disconnect() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 检查equipment_base表是否存在
    async checkTableExists() {
        try {
            console.log('🔍 检查equipment_base表是否存在...');

            const [rows] = await this.connection.execute(`
                SELECT COUNT(*) as count 
                FROM information_schema.tables 
                WHERE table_schema = '${this.dbConfig.database}' 
                AND table_name = 'equipment_base'
            `);

            const exists = rows[0].count > 0;
            console.log(`📊 equipment_base表${exists ? '存在' : '不存在'}`);
            return exists;
        } catch (error) {
            console.error('❌ 检查表存在性失败:', error.message);
            throw error;
        }
    }

    // 获取当前头盔数据
    async getCurrentHelmetData() {
        try {
            console.log('📋 获取当前头盔数据...');

            const [rows] = await this.connection.execute(`
                SELECT id, name, base, level, price, type
                FROM equipment_base 
                WHERE type = 1
                ORDER BY id
            `);

            console.log(`📊 当前表中有 ${rows.length} 条头盔数据`);
            return rows;
        } catch (error) {
            console.error('❌ 获取当前头盔数据失败:', error.message);
            throw error;
        }
    }

    // 更新头盔的base值
    async updateHelmetBase(baseValue, helmetList) {
        try {
            console.log(`🔄 开始更新头盔base=${baseValue}的数据...`);

            let successCount = 0;
            let errorCount = 0;

            for (const helmet of helmetList) {
                try {
                    const updateSQL = `
                        UPDATE equipment_base 
                        SET base = ?, level = ?, price = ? 
                        WHERE id = ? AND name = ? AND type = 1
                    `;

                    const [result] = await this.connection.execute(updateSQL, [
                        baseValue,
                        helmet.lvl,
                        helmet.price.toString(),
                        helmet.id,
                        helmet.name
                    ]);

                    if (result.affectedRows > 0) {
                        successCount++;
                        console.log(`✅ 更新头盔: ${helmet.name} (ID: ${helmet.id}) -> base=${baseValue}, lvl=${helmet.lvl}, price=${helmet.price}`);
                    } else {
                        errorCount++;
                        console.log(`⚠️ 未找到头盔: ${helmet.name} (ID: ${helmet.id})`);
                    }
                } catch (error) {
                    errorCount++;
                    console.error(`❌ 更新头盔失败 (ID: ${helmet.id}):`, error.message);
                }
            }

            console.log(`📊 base=${baseValue} 更新完成: 成功 ${successCount} 条, 失败 ${errorCount} 条`);
            return { successCount, errorCount };
        } catch (error) {
            console.error(`❌ 更新base=${baseValue}头盔失败:`, error.message);
            throw error;
        }
    }

    // 验证更新结果
    async verifyUpdate() {
        try {
            console.log('🔍 验证头盔更新结果...');

            // 按base值分组统计头盔
            const [rows] = await this.connection.execute(`
                SELECT base, COUNT(*) as count, 
                       MIN(level) as min_level, MAX(level) as max_level,
                       MIN(CAST(price AS UNSIGNED)) as min_price, MAX(CAST(price AS UNSIGNED)) as max_price
                FROM equipment_base 
                WHERE type = 1 AND base IN (1, 2, 3)
                GROUP BY base 
                ORDER BY base
            `);

            console.log('📋 按base值分组的头盔统计:');
            rows.forEach(row => {
                console.log(`   base=${row.base}: ${row.count}个头盔, 等级${row.min_level}-${row.max_level}, 价格${row.min_price}-${row.max_price}`);
            });

            // 显示每个base的前3个头盔作为示例
            for (let base = 1; base <= 3; base++) {
                const [sampleRows] = await this.connection.execute(`
                    SELECT id, name, base, level, price 
                    FROM equipment_base 
                    WHERE type = 1 AND base = ? 
                    ORDER BY level 
                    LIMIT 3
                `, [base]);

                console.log(`📋 base=${base} 前3个头盔示例:`);
                sampleRows.forEach(row => {
                    console.log(`   ID: ${row.id}, 名称: ${row.name}, 等级: ${row.level}, 价格: ${row.price}`);
                });
            }

        } catch (error) {
            console.error('❌ 验证头盔更新结果失败:', error.message);
            throw error;
        }
    }

    // 运行完整的更新流程
    async runUpdate() {
        console.log('🚀 开始更新头盔装备base值...\n');

        try {
            // 1. 连接数据库
            await this.connect();

            // 2. 检查表是否存在
            const tableExists = await this.checkTableExists();
            if (!tableExists) {
                throw new Error('equipment_base表不存在');
            }

            // 3. 获取当前头盔数据
            await this.getCurrentHelmetData();

            // 4. 更新各个base值的头盔
            let totalSuccess = 0;
            let totalError = 0;

            for (const [baseValue, helmetList] of Object.entries(helmetData)) {
                const result = await this.updateHelmetBase(parseInt(baseValue), helmetList);
                totalSuccess += result.successCount;
                totalError += result.errorCount;
                console.log(''); // 空行分隔
            }

            // 5. 验证更新结果
            await this.verifyUpdate();

            console.log('\n📊 头盔更新完成统计:');
            console.log(`   总成功: ${totalSuccess} 条`);
            console.log(`   总失败: ${totalError} 条`);
            console.log(`   总计: ${totalSuccess + totalError} 条`);

            console.log('\n🎉 头盔装备base值更新完成！');

        } catch (error) {
            console.error('\n💥 更新过程中发生错误:', error.message);
            throw error;
        } finally {
            // 6. 关闭连接
            await this.disconnect();
        }
    }
}

// 运行更新
async function main() {
    console.log('🎯 头盔装备base值更新脚本');
    console.log('   功能：根据头盔数据更新equipment_base表中对应头盔的base值\n');

    const updater = new HelmetBaseUpdater();
    await updater.runUpdate();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 更新脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = HelmetBaseUpdater;
